<?php
set_time_limit(0);

// 下载
echo '请输入56ting下载的网址:';
$url = trim(fgets(STDIN));
(new Down56Ting($url))->down();

// 改名
echo '是否需要改名字(yes/no)(有时无效):';
$ops = trim(fgets(STDIN));
if (strtolower($ops) == 'yes') {
    book_rename();
    echo '改名完成! '.PHP_EOL;
}



class Down56Ting
{
    public $base = 'http://www.ting56.com';

    public $main = '';

    public $save = './book/'; // 保存路径

    public $name = '文件名';
    
    public function __construct($url = '')
    {
        $this->main = $url;
    }

    public function down($url = '')
    {
        if (empty($url)) {
            $url = $this->main;
        }
        if (empty($url)) {
            exit('下载路径不能为空!!!');
        }
        $this->get_main($url);
    }


    /**
     * 设置文件路径
     */
    public function get_main($url)
    {
        $matchs = [];
        $html = $this->get_content($url);
        $num  = preg_match_all('/<li><a title=\'.*?\' href=\'(.*?)\'.*?>.*?<\/a><\/li>/i', $html, $matchs);
        if ($num < 1) {
            die("没有数据\n");
        }

        $paths = $matchs[1];
        $len   = count($paths);
        echo "total: $len \n";
        foreach ($paths as $path) {
            $html = $this->get_content($this->base.$path);
            $url  = $this->get_url($html);
            $this->down_file($url);
        }
        for ($i=0; $i < $len; $i++) { 
        }
        echo "Done!!! \n";
    }


    /**
     * 获取音频文件url
     */
    public function get_url($html)
    {
        // 获取文件名称
        $match = [];
        $this->name = '';
        preg_match('/var part=\'(.*?)\';/i', $html, $match);
        $this->name = $match[1];
        echo $this->name.' down ...'."\n";

        // 获取音频地址
        $match = [];
        preg_match('/FonHen_JieMa\(\'(.*?)\'\)/i', $html, $match);
        $str = '';
        $arr = explode('*', $match[1]);
        foreach ($arr as $val) {
            if (!empty($val)) {
                $str .= chr($val);
            }
        }
        $info = explode('&', $str);

        if ($info[2] == 'tc') {
            $url  = explode('/', $info[0]);
            $url  = $url[0].'/'.$url[1].'/play_'.$url[1].'_'.$url[2].'.htm';
            $http = $this->base.'/player/tingchina.php';
            $ret  = $this->get_content($http, ['url'=>$url]);
            $data = json_decode($ret, true);

            if (!is_array($data) || !array_key_exists('status', $data) || $data['status'] != 1) {
                echo "获取音频路径错误\n";
                exit;
            }
        } else {
            return $info[0];
        }
        return $data['url'];
    }


    /**
     * curl
     */
    public function get_content($url, $data = [], $cookie = [])
    {
        $ch = curl_init($url) ;
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1) ;
        if (!empty($data)) {
            curl_setopt($ch, CURLOPT_POST, 1);
            $data = http_build_query($data);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        }
        if (!empty($cookie)) {
            $cookie = http_build_cookie($cookie);
            curl_setopt($ch, CURLOPT_COOKIE, $cookie);
        }
        // header
        $header = 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) '
            .'AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.90 Safari/537.36';
        $headers[] = $header;
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        $res = curl_exec($ch) ;
        curl_close($ch) ;
        if ($res) { // 转为gb2312这一块有点问题
            $res = iconv("gbk","utf-8",$res);
        }
        return ($res);
    }


    /**
     * 下载文件
     */
    public function down_file($url)
    {
        // 转码中文
        $chinese = preg_split('/(?<!^)(?!$)/u', $url);
        $url = '';
        foreach ($chinese as $key => $value) {
            $temp = preg_match('/^[\x{4e00}-\x{9fa5}]+$/u', $value);
            $temp = $temp ? urlencode($value) : $value;
            $url .= $temp;
        }

        // 下载文件
        if (!is_dir($this->save) && !mkdir($this->save)) {
            exit("文件夹创建失败!!!\n");
        }
        $ext  = pathinfo(parse_url($url, PHP_URL_PATH), PATHINFO_EXTENSION);
        $path = $this->save . $this->name.'.'.$ext;
        if (PHP_OS == 'WINNT') {
            $path = iconv('UTF-8', 'GBK', $path);
        }

        $file = fopen($path, 'wb');
        $ch   = curl_init($url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_FILE, $file);
        curl_setopt($ch, CURLOPT_REFERER, $url);
        // header
        $header = 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) '
            .'AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.90 Safari/537.36';
        $headers[] = $header;
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);
        $res = curl_exec($ch);
        if ($ch) {
            curl_close($ch);
        }
        if ($file) {
            fclose($file);
        }
    }


    // public function resume($info = [])
    // {
    //     $temp = './temp/';
    //     if (is_dir($temp) == false) {
    //         mkdir($temp) || exit('创建临时文件夹失败!');
    //     }
    //     $name = md5($this->main);
    //     if (file_exists($temp.$name)) {
    //         $data = file_get_contents($temp.$name);
    //     };

    //     $data = json_decode($data, true);
    //     $data = array_diff($info, $data);

    //     file_put_contents($temp.$name, json_encode($info));
    //     return $data;
    // }
}



/**
 * 网上找的
 */
function checkNatInt($str) {
    $map = array(
    '一' => '1','二' => '2','三' => '3','四' => '4','五' => '5','六' => '6','七' => '7','八' => '8','九' => '9',
    '壹' => '1','贰' => '2','叁' => '3','肆' => '4','伍' => '5','陆' => '6','柒' => '7','捌' => '8','玖' => '9',
    '零' => '0','两' => '2',
    '仟' => '千','佰' => '百','拾' => '十',
    '万万' => '亿',
    ); 

    $str = str_replace(array_keys($map), array_values($map), $str);
    $str = checkString($str, '/([\d亿万千百十]+)/u');
  
    $func_c2i = function ($str, $plus = false) use(&$func_c2i) {
        if(false === $plus) {
          $plus = array('亿' => 100000000,'万' => 10000,'千' => 1000,'百' => 100,'十' => 10,);
        }  
      
        $i = 0;
        if($plus) {
            foreach($plus as $k => $v) {
                $i++;
                if(strpos($str, $k) !== false) {
                    $ex = explode($k, $str, 2); 
                    $new_plus = array_slice($plus, $i, null, true);
                    $l = $func_c2i($ex[0], $new_plus);
                    $r = $func_c2i($ex[1], $new_plus);
                    if($l == 0) $l = 1;
                    return $l * $v + $r;
                }
            }
        }
  
        return (int)$str;
    };
    return $func_c2i($str);
 }


 /**
  * 来自uct php微信开发框架，其中的checkString函数如下
  */
 function checkString($var, $check = '', $default = '') {
    if (!is_string($var)) {
        if(is_numeric($var)) {
            $var = (string)$var;
        } else {
            return $default;
        }
    }
    if ($check) {
        return (preg_match($check, $var, $ret) ? $ret[1] : $default);
    }
  
    return $var;
}


/**
 * 修改文件名字
 */
function book_rename()
{
    $base = './book/';
    $dirs = opendir($base);
    while ($filename = readdir($dirs)) {
        if ($filename == '.' || $filename == '..') {
            continue;
        }

        $pattern = '/第(.*?)(集|章|回|卷|篇|节)/i';
        $newname = preg_replace_callback($pattern , function($data){
            $num = is_numeric($data[1]) ? $data[1] :checkNatInt($data[1]);
            return sprintf('第%03d集', $num);
        } , $filename);

        rename($base.$filename, $base.$newname);
    }
}